package com.rijndael;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/**
 * @author hexjk
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: aes 对称加密
 * @date 2018/4/217:33
 */
public class AESUtil {

    public static final String logalrithm = "AES/CBC/PKCS5Padding";

    private static final String AES = "AES";

    private static final String IV_STRING = "dMitHORyqbeYVE0o";

    /**
     * 获取密钥
     *
     * @return 密钥
     * @throws NoSuchAlgorithmException
     */
    public static byte[] initKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); //192,256
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }



    /**
     * 加密
     *
     * @param content 加密内容
     * @return 密文
     * @throws Exception e
     */
    public static byte[] encrypt1(byte[] content,byte[] enCodeFormat) {
        byte[] encryptedBytes = new byte[0];
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, AES);
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            // 指定加密的算法、工作模式和填充方式
            Cipher cipher = Cipher.getInstance(logalrithm);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            encryptedBytes = cipher.doFinal(content);
        } catch (Exception e) {

           e.printStackTrace();
        }

        return  encryptedBytes;
    }

    /**
     * 解密
     *
     * @param
     * @return 明文
     * @throws Exception e
     */
    public static byte[] decrypt1(byte[] encryptedBytes,byte[] key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, AES);
        byte[] initParam = IV_STRING.getBytes();
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
        Cipher cipher = Cipher.getInstance(logalrithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] result = cipher.doFinal(encryptedBytes);
        return result;
    }
    



}
